package cn.tedu.passort.controller;


import cn.tedu.common.web.JsonResult;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@RestController
@RequestMapping("/v1")
public class UploadController {
    @Value("${file-path}")
    private String dirPath;
    @PostMapping("upload")
    public JsonResult upload(MultipartFile file) throws IOException {
        //得到文件的原始文件名
        String fileName = file.getOriginalFilename();
        //得到后缀   从最后一个.的位置截取到最后    xxxxxxx.jpg    .jpg
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        fileName = UUID.randomUUID()+suffix;//得到唯一文件名 UUID.randomUUID()得到唯一标识符
        //准备文件夹路径   d:/files/2023/10/18/xxxxx.jpg
        SimpleDateFormat dateFormat = new SimpleDateFormat("/yyyy/MM/dd/");
        String datePath = dateFormat.format(new Date());
        File dirFile = new File(dirPath+datePath);
        if (!dirFile.exists()){//如果文件夹不存在
            dirFile.mkdirs();//创建文件夹
        }
        //把文件保存到指定路径 d:/files/2023/10/18/xxxxx.jpg  //抛出异常
        // http://localhost:8080/2023/10/18/xxxxx.jpg
        file.transferTo(new File(dirPath+datePath+fileName));
        System.out.printf(datePath+"!!!!!!!!!!");
        return JsonResult.ok(datePath+fileName);
    }
    // http://localhost:8080/v1/remove?url=xxxx
    @PostMapping("remove")
    public JsonResult remove(String url){
        System.out.println("url = " + url);
        new File(dirPath+url).delete();
        return JsonResult.ok();
    }
}
